package com.firesrc.web;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.firesrc.bean.Config;
import com.firesrc.service.ConfigService;
import com.firesrc.service.impl.ConfigServiceImpl;

/**
 * Servlet implementation class ConfigServlet
 */
public class ConfigServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ConfigServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		ConfigService service = new ConfigServiceImpl();
		String type = request.getParameter("type");
		if ("add".equals(type)) {
			Config config = new Config();
			config.setName(request.getParameter("name"));
			config.setDefaultValue(request.getParameter("defaultValue"));
			config.setId(UUID.randomUUID().toString());
			config.setRemark(request.getParameter("remark"));
			config.setState(request.getParameter("state"));
			config.setValue(request.getParameter("value"));
			service.add(config);
		} else if ("update".equals(type)) {
			Config config = service.getById(request.getParameter("id"));
			request.setAttribute("config", config);
			request.getRequestDispatcher("updateConfig.jsp").forward(request, response);
			return;
		} else if ("save".equals(type)) {
			String id = request.getParameter("id");
			Config config = new Config();
			config.setId(id);
			config.setName(request.getParameter("name"));
			config.setValue(request.getParameter("value"));
			config.setDefaultValue(request.getParameter("defaultValue"));
			config.setRemark(request.getParameter("remark"));
			config.setState(request.getParameter("state"));
			service.update(config);
		}

		List<Config> allList = service.getAllList();
		request.setAttribute("list", allList);
		request.getRequestDispatcher("configList.jsp").forward(request, response);
	}

}
